import configdata from './config'
import cache from './cache'
const md5 = require('./md5.js');
var now = Date.parse(new Date()); //与header中的Send-Time一致
var salt = "jtsc";
var sign = md5.hex(now + salt); //header中X-URETAIL-AUTH的值

var ua = navigator.userAgent.toLowerCase();
var isWeixin = ua.match(/MicroMessenger/i) == "micromessenger";
let notLoad = false
// 非游客模式处理方法
async function authorizedLogin() {
	let that = this
	//通过桥接方式获取token
	const res = await getBaseInfo()
	const token = res.token2
	// alert(res.token2)
	if (token !== '') {
		// window.localStorage.setItem("user-token", token) 
		cache.put("user-token", token)
		
		getTokenStatus("http://gatewaysit.ysyec.com/iiam-14518/v1/user/oauth/check?token=" + token)
			
	} else {
		cache.clear()
		// bridgeLogin()
	}

}

function getTokenStatus(url) {
	let status = false
	window.onSuccess = function(message) {
		let object = JSON.parse(message);
		// alert('4获取用户信息成功' + message)
		// uni.showModal({
		// 	title: '提示',
		// 	content: '获取用户信息成功' + message,
		// 	success: function(res) {
		// 		if (res.confirm) {
		// 			console.log(object.loginAccount);
		// 		} else if (res.cancel) {
		// 			console.log('用户点击取消');
		// 		}
		// 	}
		// });
		getUserinfo(object.loginAccount.replace("+86-",""))
	}
	//调用失败返回
	window.onError = function(message) {
		alert('获取用户信息失败', message);
	}
	let postParam = {
		className: "BaseBridge",
		function: "getBaseInfo",
		successCallBack: "onSuccess",
		failCallBack: "onError"
	}
	
	uni.request({
		url: url,
		// data: data,
		method: "GET",
		header: {
			"content-type": "application/json;charset=UTF-8"
		},
		success: function(result) {
			if(result.data){
				HandBridge.postMessage(JSON.stringify(postParam));
			}
		},
		fail: function(e) {
			
		}
	})

}
//免密登录
function getUserinfo(val){
	// alert("user"+val)
	let url = 'https://mallmgt.inja.com/api/user/uLoginWithMobile'
	// let url = 'http://jtsc.hawkhawk.club/api/user/uLoginWithMobile'
	// let url = 'https://mallmgt.inja.com/api/user/uLoginWithMobile'
	let data = { mobile:val}
	let header = "application/json;charset=UTF-8";
	// url = this.config("OUT") + url;
	// alert("url"+url)
	uni.request({
		url: url,
		data: data,
		method: "POST",
		header: {
			"content-type": header,
			'X-URETAIL-AUTH': sign,
			'Send-Time': now
		},
		success: function(result) {
			cache.put("token", result.data.data.token)
			cache.put("userInfo", result.data.data.user)
		},
		fail: function(e) {
			error.call(self, e)
		}
	})
	
	
	
}
//获取基本信息
function getBaseInfo() {
	return new Promise((resolve, reject) => {
		console.log('开始-》获取基本信息')
		//调用成功返回
		window.onSuccess = function(message) {
			let object = JSON.parse(message);
			console.log('获取基本信息', object);
			resolve(object);
		}

		//调用失败返回
		window.onError = function(message) {
			console.log('获取基本信息失败', message);
			reject(message);
		}
		let postParam = {
			className: "BaseBridge",
			function: "getBaseInfo",
			successCallBack: "onSuccess",
			failCallBack: "onError"
		}
		HandBridge.postMessage(JSON.stringify(postParam));
	});
}
//跳转登录
async function bridgeLogin() {
	//调用成功返回
	window.loginSuccess = async function() {
		const res = await getBaseInfo()
		const token = res.token
		if (token !== '') {
			cache.put("user-token", token)
			cache.put("token", token)
		}
	}
	//调用失败返回
	window.loginError = function(message) {
		alert(message);
	}
	const loginArguments = {
		className: "BaseBridge",
		function: "login",
		successCallBack: "loginSuccess",
		failCallBack: "loginError"
	}
	HandBridge.postMessage(JSON.stringify(loginArguments));
}

module.exports = {
	config: function(name) {
		var info = null;
		if (name) {
			var name2 = name.split("."); //字符分割
			if (name2.length > 1) {
				info = configdata[name2[0]][name2[1]] || null;
			} else {
				info = configdata[name] || null;
			}
			if (info == null) {
				let web_config = cache.get("web_config");
				if (web_config) {
					if (name2.length > 1) {
						info = web_config[name2[0]][name2[1]] || null;
					} else {
						info = web_config[name] || null;
					}
				}
			}
		}
		return info;
	},
	post: function(url, data, header) {
		if(data&&data.showLogin){
			isWeixin = true
		}
		if(data&&data.notLoad){
			notLoad = data.notLoad
		}
		if (!notLoad) {
			uni.showLoading({
				title: '加载中'
			})
		}
	
		header = header || "application/json;charset=UTF-8";
		url = this.config("APIHOST") + url;
	
	
		return new Promise((succ, error) => {
			uni.request({
				url: url,
				data: data,
				method: "POST",
				header: {
					"content-type": header
				},
				success: function(result) {
					let isApp = true
					try {
						let postParam = {
							className: "BaseBridge",
							function: "getBaseInfo",
							successCallBack: "onSuccess",
							failCallBack: "onError"
						}
						HandBridge.postMessage(JSON.stringify(postParam));
					} catch (err) {
						console.log(err)
						isApp = false
					}
	
					if (isApp) {
						authorizedLogin()
					}
	
	
					succ.call(self, result.data)
					uni.hideLoading();
	
	
	
					if (result.data.code === 900) {
	
						cache.clear()
						console.log('notLoad'+url+notLoad)
						if (!isWeixin&&!notLoad) {
							uni.showModal({
								title: '提示',
								content: result.data.message,
								success: function(res) {
									if (res.confirm) {
										
										
										window.loginSuccess = function(message) {
											alert(message);
										}
										//调用失败返回
										window.loginError = function(message) {
											alert(message);
										}
										try {
											
											const loginArguments = {
												className: "BaseBridge",
												function: "login",
												successCallBack: "loginSuccess",
												failCallBack: "loginError"
											}
											HandBridge.postMessage(JSON.stringify(loginArguments));
										} catch (err) {
											console.log(err)
											uni.navigateTo({
												url: '/pages/login/login'
											})
										}
										
										// if (isApp) {
										// 	bridgeLogin()
											
										// } else {
										// 	uni.navigateTo({
										// 		url: `/pages/login/login`
										// 	})
										// }
	
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							})
						}
	
	
	
					} else if (result.data.code === 999) {
						if (!data.stopMessage) {
							uni.showModal({
								title: '提示',
								content: result.data.message,
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
	
									}
	
								}
							})
						}
	
					}
				},
				fail: function(e) {
					error.call(self, e)
				}
			})
		})
	},
	get: function(url, data, header) {
		if(data&&data.notLoad){
			notLoad = data.notLoad
		}
		if (!notLoad) {
			uni.showLoading({
				title: '加载中'
			})
		}
		
		header = header || "application/json;charset=UTF-8";
		url = this.config("APIHOST") + url;
		return new Promise((succ, error) => {
			uni.request({
				url: url,
				data: data,
				method: "GET",
				header: {
					"content-type": header
				},
				success: function(result) {
					uni.hideLoading();
					succ.call(self, result.data)
					
					if (result.data.code === 900) {
						
						cache.clear()
						if (!isWeixin) {
							uni.showModal({
								title: '提示',
								content: result.data.message,
								success: function(res) {
									if (res.confirm) {
										
										
										window.loginSuccess = async function() {
											alert(message);
										}
										//调用失败返回
										window.loginError = function(message) {
											alert(message);
										}
										try {
											
											const loginArguments = {
												className: "BaseBridge",
												function: "login",
												successCallBack: "loginSuccess",
												failCallBack: "loginError"
											}
											HandBridge.postMessage(JSON.stringify(loginArguments));
										} catch (err) {
											console.log(err)
											uni.navigateTo({
												url: '/pages/login/login'
											})
										}
										
										
						
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							})
						}
						
						
						
					}
					
				},
				fail: function(e) {
					error.call(self, e)
				}
			})
		})
	},
	post5: function(url, data, header) {
		uni.showLoading({
			title: '加载中'
		})
		header = header || "application/json;charset=UTF-8";
		url = this.config("PAY") + url;
		return new Promise((succ, error) => {
			uni.request({
				url: url,
				data: data,
				method: "POST",
				header: {
					"content-type": header
				},
				success: function(result) {
					succ.call(self, result.data)
					uni.hideLoading();
					if (result.data.code === 900) {

						uni.showModal({
							title: '提示',
							content: result.data.message,
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: `/pages/login/login`
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						})
					} else if (result.data.code === 999) {
						uni.showModal({
							title: '提示',
							content: result.data.message,
							showCancel: false,
							success: function(res) {
								if (res.confirm) {

								}

							}
						})
					}
				},
				fail: function(e) {
					error.call(self, e)
				}
			})
		})
	},
	get5: function(url, data, header) {
		uni.showLoading({
			title: '加载中'
		})
		header = header || "application/json;charset=UTF-8";
		url = this.config("PAY") + url;
		return new Promise((succ, error) => {
			uni.request({
				url: url,
				data: data,
				method: "GET",
				header: {
					"content-type": header
				},
				success: function(result) {
					uni.hideLoading();
					succ.call(self, result.data)
				},
				fail: function(e) {
					error.call(self, e)
				}
			})
		})
	},
	post1: function(url, data, header, sing) {
		uni.showLoading({
			title: '加载中'
		})
		header = header || "application/json;charset=UTF-8";
		url = this.config("USERPATH") + url;
		return new Promise((succ, error) => {
			uni.request({
				url: url,
				data: data,
				method: "POST",
				header: {
					"content-type": header,
					'X-Authorization': sing
				},
				success: function(result) {
					succ.call(self, result.data)
					uni.hideLoading();
					if (result.data.code === 900) {
						uni.showModal({
							title: '提示',
							content: result.data.message,
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: `/pages/login/login`
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						})
					} else if (result.data.code === 999) {
						uni.showModal({
							title: '提示',
							content: result.data.message,
							showCancel: false,
							success: function(res) {
								if (res.confirm) {

								}

							}
						})
					}
				},
				fail: function(e) {
					error.call(self, e)
				}
			})
		})
	},
	get1: function(url, data, header) {
		uni.showLoading({
			title: '加载中'
		})
		header = header || "application/json;charset=UTF-8";
		url = this.config("USERPATH") + url;
		return new Promise((succ, error) => {
			uni.request({
				url: url,
				data: data,
				method: "GET",
				header: {
					"content-type": header
				},
				success: function(result) {
					uni.hideLoading();
					succ.call(self, result.data)
				},
				fail: function(e) {
					error.call(self, e)
				}
			})
		})
	},
	post3: function(url, data, header, sing) {
		uni.showLoading({
			title: '加载中'
		})
		header = header || "application/json;charset=UTF-8";
		url = this.config("URL") + url;
		return new Promise((succ, error) => {
			uni.request({
				url: url,
				data: data,
				method: "POST",
				header: {
					"content-type": header
				},
				success: function(result) {
					succ.call(self, result.data)
					uni.hideLoading();
					if (result.data.code === 900) {
						uni.showModal({
							title: '提示',
							content: result.data.message,
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: `/pages/login/login`
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						})
					} else if (result.data.code === 999) {
						uni.showModal({
							title: '提示',
							content: result.data.message,
							showCancel: false,
							success: function(res) {
								if (res.confirm) {

								}

							}
						})
					}
				},
				fail: function(e) {
					error.call(self, e)
				}
			})
		})
	},
	get3: function(url, data, header) {
		uni.showLoading({
			title: '加载中'
		})
		header = header || "application/json;charset=UTF-8";
		url = this.config("URL") + url;
		return new Promise((succ, error) => {
			uni.request({
				url: url,
				data: data,
				method: "GET",
				header: {
					"content-type": header
				},
				success: function(result) {
					uni.hideLoading();
					succ.call(self, result.data)
				},
				fail: function(e) {
					error.call(self, e)
				}
			})
		})
	},
	get4: function(url, data, header) {
		uni.showLoading({
			title: '加载中'
		})
		header = header || "application/json;charset=UTF-8";
		url = this.config("OUT") + url;
		return new Promise((succ, error) => {
			uni.request({
				url: url,
				data: data,
				method: "GET",
				header: {
					"content-type": header
				},
				success: function(result) {
					uni.hideLoading();
					succ.call(self, result.data)
				},
				fail: function(e) {
					error.call(self, e)
				}
			})
		})
	},
	post4: function(url, data, header, sing) {
		if(data&&data.notLoad){
			notLoad = data.notLoad
		}
		if (!notLoad) {
			uni.showLoading({
				title: '加载中'
			})
		}
		header = header || "application/json;charset=UTF-8";
		url = this.config("OUT") + url;
		return new Promise((succ, error) => {
			uni.request({
				url: url,
				data: data,
				method: "POST",
				header: {
					"content-type": header,
					'X-URETAIL-AUTH': sign,
					'Send-Time': now
				},
				success: function(result) {
					succ.call(self, result.data)
					uni.hideLoading();
					
					
					if (result.data.code === 900) {
						cache.clear()
						if (!isWeixin) {
							uni.showModal({
								title: '提示',
								content: result.data.message,
								success: function(res) {
									if (res.confirm) {
										uni.navigateTo({
											url: `/pages/login/login`
										})
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							})
						}
						
					} else if (result.data.code === 0) {
						// uni.showModal({
						// 	title:'提示',
						// 	content:result.data.message||result.data.msg,
						// 	showCancel:false,
						// 	success:function(res){
						// 		if(res.confirm){

						// 		}

						// 	}
						// })
					}
				},
				fail: function(e) {
					error.call(self, e)
				}
			})
		})
	}
}
